﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace QuanLyPhongKham
{
    public partial class QuanLyNhaThuoc : BaseUserControl
    {
        private DAL.AccessData m;
        private doiso.Doisototext doiso = new doiso.Doisototext();
        private string sql = "", user = "", s_mabn = "", s_mmyy = "", s_makho = "", s_manguon = "", s_ngay = "", s_userid = "";
        private long l_maql = 0, l_id = 0, l_sttt = 0;
        private int i_userid = 1, i_mabd, i_row;
        private bool bNew, bEdit;
        private decimal d_soluong, d_giaban, d_dongia, d_sotien, d_sotienban, d_soluongcu, d_sotiencu, d_tongcong, d_soluongton;
        private DataTable dtll = new DataTable();
        private DataTable dtct = new DataTable();
        private DataTable dtton = new DataTable();
        private DataTable dttonct = new DataTable();
        private DataTable dtthem = new DataTable();
        private DataTable dtxoa = new DataTable();
        private DataTable dtsave = new DataTable();
        private DataSet ds = new DataSet();
        private DataSet dsxml = new DataSet();
        public QuanLyNhaThuoc()
        {
            InitializeComponent();
        }
        private void lTen_DoubleClick(object sender, EventArgs e)
        {
            //frmAbout f = new frmAbout(pForm.Location.X,pForm.Location.Y,lTen.Text,m);
            //f.ShowDialog();
            //load_tieude();
        }
        private void QuanLyPhongKham_Load(object sender, EventArgs e)
        {
            //load_tonct();
            var f = this.FormMain.FormLogin;

            if (f.i_userid != 0)
            {
                m = f.m;
                s_userid = f.s_hoten;
                s_mmyy = f.s_mmyy;
                s_ngay = f.s_ngay;
                user = m.user;
                if (!m.bMmyy(s_mmyy))
                {
                    m.tao_table(s_mmyy);
                    m.tao_function(s_mmyy);
                    m.upd_table(s_mmyy, i_userid);
                }
                m.execute_data("update " + user + ".d_tonkhoct_" + s_mmyy + " set tondau=0 where tondau is null");
                m.execute_data("update " + user + ".d_tonkhoct_" + s_mmyy + " set slnhap=0 where slnhap is null");
                m.execute_data("update " + user + ".d_tonkhoct_" + s_mmyy + " set slxuat=0 where slxuat is null");
                m.execute_data("update " + user + ".d_tonkhoth_" + s_mmyy + " set tondau=0 where tondau is null");
                m.execute_data("update " + user + ".d_tonkhoth_" + s_mmyy + " set slnhap=0 where slnhap is null");
                m.execute_data("update " + user + ".d_tonkhoth_" + s_mmyy + " set slxuat=0 where slxuat is null");
                m.execute_data("delete from " + user + ".d_tonkhoct_" + s_mmyy + " where tondau=0 and slnhap=0 and slxuat=0");
                m.execute_data("delete from " + user + ".d_tonkhoth_" + s_mmyy + " where tondau=0 and slnhap=0 and slxuat=0");
                cboMabn.DisplayMember = "MABN";
                cboMabn.ValueMember = "MAQL";
                load_tieude();
                listthuoc.DisplayMember = "TEN";
                listthuoc.ValueMember = "STT";
                //load_dmbd();
                cboMabn.DisplayMember = "MABN";
                cboMabn.ValueMember = "ID";
                load_sophieu();
                if (dtll.Rows.Count == 0)
                {
                    load_head();
                    load_grid();
                }
                reft_text();
                cboMabn.BringToFront();
                AddGridTableStyle();
                ena_object(false);
                ena_button(false);
                cboMabn.Focus();
            }
            else Application.Exit();
        }
        private void load_dmbd()
        {
            dtton = m.get_tonkhoth(s_mmyy, s_makho, s_manguon);
            listthuoc.DataSource = dtton;
        }
        private void load_tonct()
        {
            dttonct = m.get_tonkhoct(s_mmyy, s_makho, s_manguon);
        }
        private void load_sophieu()
        {
            sql = "select a.id,a.sotoa,a.mabn,a.maql,a.hoten,a.namsinh,a.phai,to_char(a.ngay,'dd/mm/yyyy') as ngay,a.userid,a.makp,b.tenkp,a.mabs,c.hoten as tenbs,a.maicd,a.chandoan from "+user+".d_toathuocll_"+s_mmyy+" a left join "+user+".btdkp b on a.makp=b.makp left join "+user+".dmbs c on a.mabs=c.ma where to_char(a.ngay,'dd/mm/yyyy')='"+s_ngay+"'";
            var ds = m.get_data(sql);
            if (ds.Tables.Count > 0)
            {
                dtll = ds.Tables[0];
                cboMabn.DataSource = dtll;
            }
        }
        private void load_grid()
        {
            dataGrid1.DataSource = null;
            sql = "select a.mabd,a.stt,a.sttt,b.ma,trim(b.ten)||' '||b.hamluong as ten,b.tenhc,b.dang,a.handung,a.losx,a.manguon, d.ten as tennguon,a.madv,c.ten as tenncc,a.makho,a.soluong,round(a.giaban,2) as giaban,round(a.giamua,2) as giamua,round(a.soluong*a.giaban,2) as sotienban,a.soluong as soluongcu,a.soluong*a.giaban as sotiencu ";
            sql += " from " + user + ".d_toathuocct_"+s_mmyy+" a," + user + ".d_dmbd b," + user + ".d_dmnx c, "+user+".d_dmnguon d where a.mabd=b.id and a.madv=c.id(+) and a.manguon=d.id and a.id=" + l_id + " order by a.stt";
            var ds = m.get_data(sql);
            if (ds.Tables.Count > 0)
            {
                dtct = ds.Tables[0];
                dtxoa = dtct.Clone();
                dtthem = dtct.Clone();
                dataGrid1.DataSource = dtct;
            }
        }
        private void AddGridTableStyle()
        {
            DataGridColoredTextBoxColumn TextCol;
            delegateGetColorRowCol de = new delegateGetColorRowCol(MyGetColorRowCol);
            DataGridTableStyle ts = new DataGridTableStyle();
            ts.MappingName = dtct.TableName;
            ts.AlternatingBackColor = Color.Linen;
            ts.BackColor = Color.GhostWhite;
            ts.ForeColor = Color.MidnightBlue;
            ts.GridLineColor = SystemColors.Control;
            ts.HeaderBackColor = SystemColors.Control;
            ts.HeaderForeColor = Color.Navy;
            ts.SelectionBackColor = Color.Teal;
            ts.SelectionForeColor = Color.White;
            ts.ReadOnly = false;
            ts.RowHeaderWidth = 5;
            ts.AllowSorting = false;

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "stt";
            TextCol.HeaderText = "Stt";
            TextCol.Width = 0;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 1);
            TextCol.MappingName = "sttt";
            TextCol.HeaderText = "";
            TextCol.Width = 0;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 2);
            TextCol.MappingName = "mabd";
            TextCol.HeaderText = "";
            TextCol.Width = 0;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 3);
            TextCol.MappingName = "ma";
            TextCol.HeaderText = "Mã số";
            TextCol.Width = 80;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 4);
            TextCol.MappingName = "ten";
            TextCol.HeaderText = "Tên thuốc - hàm lượng";
            TextCol.Width = 400;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 5);
            TextCol.MappingName = "tenhc";
            TextCol.HeaderText = "Hoạt chất";
            TextCol.Width = 200;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 6);
            TextCol.MappingName = "dang";
            TextCol.HeaderText = "ĐVT";
            TextCol.Width = 60;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);
            
            TextCol = new DataGridColoredTextBoxColumn(de, 7);
            TextCol.MappingName = "handung";
            TextCol.HeaderText = "";
            TextCol.Width = 0;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 8);
            TextCol.MappingName = "losx";
            TextCol.HeaderText = "";
            TextCol.Width = 0;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 9);
            TextCol.MappingName = "manguon";
            TextCol.HeaderText = "";
            TextCol.Width = 0;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 10);
            TextCol.MappingName = "tennguon";
            TextCol.HeaderText = "";
            TextCol.Width = 0;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 11);
            TextCol.MappingName = "tenncc";
            TextCol.HeaderText = "";
            TextCol.Width = 0;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 12);
            TextCol.MappingName = "soluong";
            TextCol.HeaderText = "Số lượng";
            TextCol.Width = 70;
            TextCol.Format = "###,###,###,##0";
            TextCol.Alignment = HorizontalAlignment.Right;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 13);
            TextCol.MappingName = "giaban";
            TextCol.HeaderText = "Giá bán";
            TextCol.Width = 110;
            TextCol.Format = "###,###,###,##0.00";
            TextCol.Alignment = HorizontalAlignment.Right;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 14);
            TextCol.MappingName = "sotienban";
            TextCol.HeaderText = "Số tiền";
            TextCol.Width = 160;
            TextCol.Format = "###,###,###,##0.00"; 
            TextCol.Alignment = HorizontalAlignment.Right;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 15);
            TextCol.MappingName = "soluongcu";
            TextCol.HeaderText = "";
            TextCol.Width = 0;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 16);
            TextCol.MappingName = "makho";
            TextCol.HeaderText = "";
            TextCol.Width = 0;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);
        }
        public Color MyGetColorRowCol(int row, int col)
        {
            Color c = Color.Navy;
            return c;
        }
        public delegate Color delegateGetColorRowCol(int row, int col);
        public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn
        {
            private delegateGetColorRowCol _getColorRowCol;
            private int _column;
            public DataGridColoredTextBoxColumn(delegateGetColorRowCol getcolorRowCol, int column)
            {
                _getColorRowCol = getcolorRowCol;
                _column = column;
            }
            protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
            {
                try
                {
                    foreBrush = new SolidBrush(_getColorRowCol(rowNum, this._column));
                }

                catch { }
                finally
                {
                    base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
                }
            }
        }
        private void load_head()
        {
            DataRow r = m.getrowbyid(dtll, "id=" + l_id);
            if (r != null)
            {
                l_maql = long.Parse(r["maql"].ToString());
                mabn.Text = r["mabn"].ToString();
                hoten.Text = r["hoten"].ToString();
                namsinh.Text = r["namsinh"].ToString();
                if (r["phai"].ToString() == "1" || r["phai"].ToString() == "0") cboGioitinh.SelectedIndex = int.Parse(r["phai"].ToString());
                else cboGioitinh.SelectedIndex = -1;
                mabs.Text = r["mabs"].ToString();
                tenbs.Text = r["tenbs"].ToString();
                makp.Text = r["makp"].ToString();
                tenkp.Text = r["tenkp"].ToString();
                maicd.Text = r["maicd"].ToString();
                icd.Text = r["chandoan"].ToString();
                toaso.Text = r["sotoa"].ToString();
            }
        }
        private void load_tieude()
        {
            if (System.IO.File.Exists(@"..\..\..\xml\t_thongso.xml"))
            {
                dsxml.ReadXml(@"..\..\..\xml\t_thongso.xml");
                lTen.Text = dsxml.Tables[0].Rows[0]["c1"].ToString().ToUpper();
                lDiachi.Text = dsxml.Tables[0].Rows[0]["c2"].ToString();
            }
        }
        private void QuanLyPhongKham_SizeChanged(object sender, EventArgs e)
        {
            bNut.Location = new Point((this.Width - 800) / 2 -10, 2);
        }
        private void mabn_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    ComboBox cb = (ComboBox)sender;
                    if (cb.SelectedIndex == -1) cb.SelectedIndex = 0;
                    SendKeys.Send("{Tab}{F4}");
                }
                catch { SendKeys.Send("{Tab}{F4}"); }
            }
        }
        private void butKetthuc_Click(object sender, EventArgs e)
        {
            
        }
        private void butMoi_Click(object sender, EventArgs e)
        {
            if (m.bKhoaso(s_mmyy))
            {
                MessageBox.Show("Số liệu tháng" + s_mmyy.Substring(0, 2) + " năm " + s_mmyy.Substring(2, 2) + "đã khóa !\nNếu cần thay đổi thì vào mục khai báo hệ thống!", DAL.AccessData.Msg);
                return;
            }
            if (dtton.Rows.Count == 0) load_dmbd();
            bNew = true; bEdit = false;
            emp_detail(); emp_head();
            mabn.BringToFront();
            mabn.Text = ""; mabn.Focus(); sotientong.Text = "0"; chutien.Text = "";
            l_maql = 0; l_id = 0;
            dtct.Clear(); dtsave.Clear(); dtxoa.Clear(); dtthem.Clear();
            dataGrid1.Refresh();
            ena_button(true);
            ena_object(true);
            toaso.Text= m.get_sotoa_xuatban(s_mmyy, s_ngay).ToString();
            tenthuoc.Focus();
        }
        private void butBoqua_Click(object sender, EventArgs e)
        {
            bNew = false; bEdit = false;
            try
            {
                if (cboMabn.Items.Count > 0) l_id = long.Parse(cboMabn.SelectedValue.ToString());
                else l_id = 0;
                load_head(); load_grid(); reft_text(); sum_sotienban();
            }
            catch { }
            ena_button(false);
            ena_object(false); butMoi.Focus();
        }
        private void load_diungthuoc()
        {
            string s_thuocdiung = "";
            int iMucdo_Max = 1;
            sql = "select a.mucdo,b.tenhc from " + user + ".d_diungthuoc a,"+user+".d_dmhoatchat b where a.mahc=b.mahc and a.mabn='" + s_mabn + "'";
            foreach (DataRow r in m.get_data(sql).Tables[0].Rows)
            {
                iMucdo_Max = (int.Parse(r["mucdo"].ToString())>iMucdo_Max)?int.Parse(r["mucdo"].ToString()):iMucdo_Max;
                s_thuocdiung+=r["tenhc"].ToString()+", ";
            }
            if (s_thuocdiung != "")
            {
                switch (iMucdo_Max)
                {
                    case 1: butTrathuoc.BackColor = Color.Pink; break;
                    case 2: butTrathuoc.BackColor = Color.Yellow; break;
                    case 3: butTrathuoc.BackColor = Color.Red;
                        butTrathuoc.ForeColor = Color.Blue;
                        break;
                }
                lChon.Text += "-->Dị ứng hoạt chất thuốc :" + s_thuocdiung.Trim().Trim(',');
            }
        }
        private void MaskDigit(KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || e.KeyChar == 8 || e.KeyChar == '/' || e.KeyChar == '.') e.Handled = false;
            else e.Handled = true;
        }
        private void mabn_KeyPress(object sender, KeyPressEventArgs e)
        {
            MaskDigit(e);
        }
        private void mabn2_Validated(object sender, EventArgs e)
        {
            if (mabn.Text.Trim() == "")
            {
                if (MessageBox.Show("Bạn chưa nhập mã bệnh nhân!\nBạn có muốn tiếp tục bán không?", DAL.AccessData.Msg, MessageBoxButtons.YesNo,MessageBoxIcon.Information, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    mabn.Text = m.get_sotoa_xuatban(s_mmyy, s_ngay).ToString();
                    toaso.Text = mabn.Text;
                    mathuoc.Focus();
                }
            }
            if (mabn.Text.Trim() != "" && mabn.Text.Trim().Length < 3)
            {
                return;
            }
            else if (mabn.Text.Trim() != "" && mabn.Text.Trim().Length >= 3)
            {
                mabn.Text = mabn.Text.Substring(0, 2) + mabn.Text.Substring(2).PadLeft(6, '0');
                if (load_mabn())
                {
                    if (load_vv_mabn())
                    {
                        if (get_donthuoc())
                        {
                            ena_button(true);
                            butLuu.Focus();
                        }
                        else mathuoc.Focus();
                        toaso.Text = m.get_sotoa_xuatban(s_mmyy, s_ngay).ToString();
                    }
                    else
                    {
                        MessageBox.Show("Không tìm thấy thông tin khám của bệnh nhân!", DAL.AccessData.Msg);
                        mabn.Focus();
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("Không tìm thấy thông tin hành chính bệnh nhân!", DAL.AccessData.Msg);
                    mabn.Focus();
                    return;
                }
            }
        }
        private bool load_mabn()
        {
            bool ret = false;
            foreach (DataRow r in m.get_data("select * from "+user+".btdbn where mabn='" + mabn.Text + "'").Tables[0].Rows)
            {
                mabn.Text = r["mabn"].ToString();
                hoten.Text = r["hoten"].ToString();
                namsinh.Text = r["namsinh"].ToString();
                cboGioitinh.SelectedIndex = int.Parse(r["phai"].ToString());
                ret = true;
                break;
            }
            return ret;
        }
        private bool load_vv_mabn()
        {
            sql = "select a.mabn,a.maql,a.maicd,a.chandoan,a.mabs,c.hoten,a.makp,b.tenkp from " + user + ".benhanpk a inner join " + user + ".btdkp b on a.makp=b.makp inner join " + user + ".dmbs c on a.mabs=c.ma where a.mabn='" + mabn.Text + "' and to_char(a.ngay,'dd/mm/yyyy')='" + s_ngay + "'";
            foreach (DataRow r in m.get_data(sql).Tables[0].Rows)
            {
                l_maql = long.Parse(r["maql"].ToString());
                makp.Text = r["makp"].ToString();
                tenkp.Text = r["tenkp"].ToString();
                mabs.Text = r["mabs"].ToString();
                tenbs.Text = r["hoten"].ToString();
                maicd.Text = r["maicd"].ToString();
                icd.Text = r["chandoan"].ToString();
                return true;
            }
            return false;
        }
        private bool get_donthuoc()
        {
            sql = "select b.mabd,b.stt,0 as sttt,c.ma,trim(c.ten||' '||c.hamluong) as ten,c.tenhc,c.dang,'' as handung,'' as losx,b.manguon,d.ten as tennguon,e.id madv,e.ten as tenncc,b.makho,b.soluong,0 as giaban,0 as sotienban,b.soluong as soluongcu,0 as sotiencu";
            sql+=" from " + user + ".d_donthuocll_" + s_mmyy + " a, " + user + ".d_donthuocct_" + s_mmyy + " b, " + user + ".d_dmbd c, " + user + ".d_dmnguon d, " + user + ".d_dmnx e where a.id=b.id and b.mabd=c.id and b.manguon=d.id(+) and c.madv=e.id(+) and a.mabn='" + mabn.Text + "' and a.maql=" + l_maql;
            foreach (DataRow r in m.get_data(sql).Tables[0].Rows)
            {
                m.updrec_toathuocct(dtct, long.Parse(r["stt"].ToString()), long.Parse(r["sttt"].ToString()), int.Parse(r["mabd"].ToString()), r["ma"].ToString(), r["ten"].ToString(), r["tenhc"].ToString(), r["dang"].ToString(), 
                    r["tennguon"].ToString(), r["tenncc"].ToString(), r["handung"].ToString(), r["losx"].ToString(), decimal.Parse(r["soluong"].ToString()), decimal.Parse(r["giaban"].ToString()), decimal.Parse(r["sotienban"].ToString()), int.Parse(r["makho"].ToString()), int.Parse(r["manguon"].ToString()), dtton, decimal.Parse(r["soluongcu"].ToString()), decimal.Parse(r["sotiencu"].ToString()));
            }
            dtct.AcceptChanges(); dataGrid1.Refresh();
            //dataGrid1.DataSource = dtct;
            return dtct.Rows.Count > 0;
        }
        private bool IsLoaded(string frm)
        {
            //Form[] afrm = this.MdiChildren;
            //foreach (Form f in afrm)
            //{
            //    if (f.Name.Equals(frm)) { f.Activate(); f.BringToFront(); pForm.SendToBack(); pPhieukham.Visible = false; return true; }
            //}
            return false;

        }
        private void QuanLyPhongKham_MdiChildActivate(object sender, EventArgs e)
        {
            pForm.BringToFront();
            pPhieukham.Visible = true;
            lChon.Text = "      PHIẾU BÁN THUỐC";
            butNhapkho.BackColor = Color.MintCream;
            butXuatkho.BackColor = Color.MintCream;
            butTrathuoc.BackColor = Color.MintCream;
            //0949203050 : Hồng, 86:
        }
        private void mnuDmthuoc_Click(object sender, EventArgs e)
        {
            
            frmDmthuoc f = new frmDmthuoc(m,i_userid,s_mmyy);
            //f.MdiParent = this;
            f.Show();
            //f.ShowInTaskbar = false;
            f.Dock = DockStyle.Fill;
            f.BringToFront();
            f.Left = pForm.Left;
            f.Top = pForm.Top;
            f.Height = pForm.Height;
            f.Width = pForm.Width;
            pForm.SendToBack();
            pPhieukham.Visible = false;
            lChon.Text = "      " + mnuDmthuoc.Text.ToUpper();
        }
        private void butVienphi_Click(object sender, EventArgs e)
        {
           
        }
        private void mnuDmnhom_Click(object sender, EventArgs e)
        {
            frmDmnhom f = new frmDmnhom(m, "d_dmnhom", "id", "ten", "Mã nhóm", "Tên nhóm", 2, "Danh mục nhóm", "manhom");
            //f.ShowDialog();
        }
        private void mnuDmnuocsx_Click(object sender, EventArgs e)
        {
            frmDmnhom f = new frmDmnhom(m, "d_dmnuoc", "id", "ten", "Mã nước", "Tên nước", 4, "Danh mục nước sản xuất", "manuoc");
            //f.ShowDialog();
        }
        private void mnuDmhangsx_Click(object sender, EventArgs e)
        {
            frmDmnhom f = new frmDmnhom(m, "d_dmhang", "id", "ten", "Mã hãng", "Tên hãng", 3, "Danh mục hãng sản xuất", "mahang");
            //f.ShowDialog();
        }
        private void mnuDmnhacc_Click(object sender, EventArgs e)
        {
            frmDmnhom f = new frmDmnhom(m, "d_dmnx", "id", "ten", "Mã NCC", "Tên NCC", 5, "Danh mục nhà cung cấp", "madv");
            //f.ShowDialog();
        }
        private void mnuDmhoatchat_Click(object sender, EventArgs e)
        {
            frmDmnhom f = new frmDmnhom(m, "d_dmhoatchat", "mahc", "tenhc", "Mã HC", "Hoạt chất", 6, "Danh mục hoạt chất", "mahc");
            //f.ShowDialog();
        }
        private void timkiem_MouseDown(object sender, MouseEventArgs e)
        {
            if (timkiem.Text.Trim() == "Tìm kiếm")
            {
                timkiem.Text = "";
            }
        }
        private void timkiem_Validated(object sender, EventArgs e)
        {
            if (timkiem.Text == "")
            {
                timkiem.Text = "Tìm kiếm";
            }
        }
        private void cboMabn_SelectedIndexChanged(object sender, EventArgs e)
        {
            try 
            {
                l_id = long.Parse(cboMabn.SelectedValue.ToString());
                load_head();
                load_grid();
                reft_text();
                sum_sotienban();
            }
            catch { l_maql = 0; }
        }
        private void emp_detail()
        {
            stt.Text = ""; sttt.Text = ""; makho.Text = ""; manguon.Text = "";
            mathuoc.Text = "";
            tenthuoc.Text = "";
            hoatchat.Text = "";
            dvt.Text = "";
            soluong.Text = "0";
            giamua.Text = "0";
            sotienban.Text = "0";
            handung.Text = "";
            losx.Text = "";
            giaban.Text = "0";
            nguon.Text = "";
            nhacc.Text = "";
            d_soluongcu = 0;
            d_sotiencu = 0;
        }
        private void emp_head()
        {
            hoten.Text = "";
            namsinh.Text = "";
            mabs.Text = ""; tenbs.Text = ""; makp.Text = ""; tenkp.Text = ""; maicd.Text = ""; icd.Text = "";
        }
        private void ena_object(bool ena)
        {
            mabn.Visible = ena;
            cboMabn.Visible = !ena;
            mabn.BringToFront();
            cboMabn.BringToFront();
            //hoten.Enabled = ena;
            //makp.Enabled = ena;
            //mabs.Enabled = ena;
            //tenkp.Enabled = ena;
            //tenbs.Enabled = ena;
            //namsinh.Enabled = ena;
            //cboGioitinh.Enabled = ena;
            //maicd.Enabled = ena;
            //icd.Enabled = maicd.Enabled;
            mathuoc.Enabled = ena;
            tenthuoc.Enabled = ena;
            soluong.Enabled = ena;
        }
        private void ena_button(bool ena)
        {
            butMoi.Enabled = !ena;
            butSua.Enabled = !ena;
            butThem.Enabled = ena;
            butXoa.Enabled = ena;
            butLuu.Enabled = ena;
            butBoqua.Enabled = ena;
            butHuy.Enabled = !ena;
            butIn.Enabled = !ena;
            butKetthuc.Enabled = !ena;
            if (ena) load_dmbd();
            dataGrid1.ReadOnly = !ena;
            if (dtct.Rows.Count > 0)
            {
                CurrencyManager cm = (CurrencyManager)BindingContext[dataGrid1.DataSource, dataGrid1.DataMember];
                DataView dv = (DataView)cm.List;
            }
        }
        private void butThem_Click(object sender, EventArgs e)
        {
            if (kiemtra())
            {
                d_soluong = (soluong.Text != "") ? decimal.Parse(soluong.Text) : 0;
                d_dongia = (giamua.Text != "") ? decimal.Parse(giamua.Text) : 0;
                d_sotien = (sotienban.Text != "") ? decimal.Parse(sotienban.Text) : 0;
                d_giaban = (giaban.Text != "") ? decimal.Parse(giaban.Text) : 0;
                l_sttt = (sttt.Text != "") ? long.Parse(sttt.Text) : 0;
                if (bEdit)
                {
                    m.updrec_toathuocct(dtthem, long.Parse(stt.Text), l_sttt, i_mabd, mathuoc.Text, tenthuoc.Text, hoatchat.Text, dvt.Text, nguon.Text, nhacc.Text, handung.Text, losx.Text, d_soluongcu, d_giaban, Math.Round(d_soluongcu * d_giaban, 3), int.Parse(makho.Text), int.Parse(manguon.Text), dtton, d_soluongcu, d_sotiencu);
                    l_sttt = 0;
                }
                m.updrec_toathuocct(dtct, long.Parse(stt.Text), l_sttt, i_mabd, mathuoc.Text, tenthuoc.Text, hoatchat.Text, dvt.Text, nguon.Text, nhacc.Text, handung.Text, losx.Text, d_soluong, d_giaban, Math.Round(d_soluong * d_giaban, 3), int.Parse(makho.Text), int.Parse(manguon.Text), dtton, d_soluongcu, d_sotiencu);
                dtct.AcceptChanges();
                dataGrid1.Refresh();
                sum_sotienban();
                emp_detail();
                mathuoc.Focus();
            }
        }
        private bool kiemtra()
        {
            if (mathuoc.Text == "" || tenthuoc.Text == "")
            {
                mathuoc.Focus(); return false;
            }
            DataRow r = m.getrowbyid(dtton, "ma='" + mathuoc.Text + "'");
            if (r == null)
            {
                MessageBox.Show("Mã số không hợp lệ !", DAL.AccessData.Msg);
                tenthuoc.Focus();
                return false;
            }
            i_mabd = int.Parse(r["id"].ToString());
            return true;
        }
        private void butSua_Click(object sender, EventArgs e)
        {
            if (m.bKhoaso(s_mmyy))
            {
                MessageBox.Show("Số liệu tháng" + s_mmyy.Substring(0, 2) + " năm " + s_mmyy.Substring(2, 2) + "đã khóa !\nNếu cần thay đổi thì vào mục khai báo hệ thống!", DAL.AccessData.Msg);
                return;
            }
            if (dtct.Rows.Count <= 0 || l_id == 0) return;
            if (m.get_data("select idduyet from " + m.user + ".d_toathuocll_" + s_mmyy + " where idduyet <>0 and mabn='" + mabn.Text.Trim() + "'").Tables[0].Rows.Count > 0)
            {
                MessageBox.Show("Toa thuốc này đã được trả, không được sửa !");
                mabn.Focus();
                return;
            }
            cboMabn.Visible = false; mabn.Visible = true; mabn.BringToFront();
            ena_object(true);
            bEdit = true; bNew = false;
            dtxoa.Clear(); dtthem.Clear();
            dtsave = dtct.Copy();
            ena_button(true);
            reft_text();
        }
        private void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
        {
            try
            {
                if (dataGrid1.CurrentCell.ColumnNumber == 12 && i_row < dtct.Rows.Count)
                {
                    if (!bNew)
                    {
                        if (decimal.Parse(dataGrid1[i_row, 12].ToString()) != d_soluongcu)
                        {
                            m.updrec_toathuocct(dtxoa, int.Parse(stt.Text), long.Parse(dataGrid1[i_row, 1].ToString()), i_mabd, mathuoc.Text, tenthuoc.Text, hoatchat.Text, dvt.Text, nguon.Text, nhacc.Text, handung.Text, losx.Text, d_soluongcu, d_giaban, Math.Round(d_soluongcu * d_giaban, 3), int.Parse(makho.Text), int.Parse(manguon.Text), dtton, d_soluongcu, d_sotiencu);
                            dataGrid1[i_row, 1] = 0;
                        }
                    }
                    if (dataGrid1[i_row, 1].ToString() != "0")
                    {
                        if (decimal.Parse(dataGrid1[i_row, 12].ToString()) > decimal.Parse(dataGrid1[i_row, 15].ToString()))
                            dataGrid1[i_row, dataGrid1.CurrentCell.ColumnNumber] = decimal.Parse(dataGrid1[i_row, 15].ToString());
                    }
                    else
                    {
                        DataRow r = m.getrowbyid(dtton, "ma='" + dataGrid1[i_row, 3].ToString() + "'");
                        if (r != null)
                        {
                            i_mabd = int.Parse(r["id"].ToString());
                            d_soluongton = m.get_slton_nguon(dtton, int.Parse(dataGrid1[i_row, 16].ToString()), i_mabd, int.Parse(dataGrid1[i_row, 9].ToString()), decimal.Parse(dataGrid1[i_row, 15].ToString()));
                            if (decimal.Parse(dataGrid1[i_row, 12].ToString()) > d_soluongton)
                            {
                                MessageBox.Show("Số lượng xuất lớn hơn số lượng tồn !(" + d_soluongton.ToString() + ")", DAL.AccessData.Msg);
                                dataGrid1[i_row, dataGrid1.CurrentCell.ColumnNumber] = 0;
                            }
                        }
                    }
                    upd_rec(int.Parse(dataGrid1[i_row, 0].ToString()), decimal.Parse(dataGrid1[i_row, 12].ToString()) * decimal.Parse(dataGrid1[i_row, 13].ToString()));
                }
                i_row = dataGrid1.CurrentRowIndex;
            }
            catch { }
            reft_text();
        }
        private void reft_text()
        {
            try
            {
                int i = dataGrid1.CurrentCell.RowNumber;
                stt.Text = dataGrid1[i, 0].ToString();
                sttt.Text = dataGrid1[i, 1].ToString();
                i_mabd=int.Parse(dataGrid1[i, 2].ToString());
                mathuoc.Text = dataGrid1[i, 3].ToString();
                tenthuoc.Text = dataGrid1[i, 4].ToString();
                hoatchat.Text = dataGrid1[i, 5].ToString();
                dvt.Text = dataGrid1[i, 6].ToString();
                handung.Text = dataGrid1[i, 7].ToString();
                losx.Text = dataGrid1[i, 8].ToString();
                manguon.Text = dataGrid1[i, 9].ToString();
                nguon.Text = dataGrid1[i, 10].ToString();
                nhacc.Text = dataGrid1[i, 11].ToString();
                makho.Text = dataGrid1[i, 16].ToString();
                d_soluong = (dataGrid1[i, 12].ToString() != "") ? decimal.Parse(dataGrid1[i, 12].ToString()) : 0;
                d_dongia = (dataGrid1[i, 13].ToString() != "") ? decimal.Parse(dataGrid1[i, 13].ToString()) : 0;
                d_sotien = (dataGrid1[i, 14].ToString() != "") ? decimal.Parse(dataGrid1[i, 14].ToString()) : 0;
                d_giaban = (dataGrid1[i, 13].ToString() != "") ? decimal.Parse(dataGrid1[i, 13].ToString()) : 0;
                soluong.Text = d_soluong.ToString("#,###,###,##0");
                giamua.Text = d_dongia.ToString("#,###,###,##0");
                sotien.Text = d_sotien.ToString("#,###,###,##0");
                giaban.Text = d_giaban.ToString("#,###,###,##0");
                d_sotienban = d_soluong * d_giaban;
                dataGrid1[i, 14] = d_sotienban;
                sotienban.Text = d_sotienban.ToString("#,###,###,##0");
                d_soluongcu = (bNew) ? 0 : d_soluong;
                d_sotiencu = d_sotien;
                //if (butLuu.Enabled)
                //{
                //    tenthuoc.Enabled = sttt.Text == "0";
                //    mathuoc.Enabled = tenthuoc.Enabled;
                //    sum_sotienban();
                //}
            }
            catch { }
        }
        private void upd_rec(int stt, decimal sotien)
        {
            DataRow[] dr = dtct.Select("stt=" + stt);
            if (dr.Length > 0) dr[0]["sotienban"] = sotien;
            sum_sotienban();
        }
        private void sum_sotienban()
        {
            d_tongcong = 0;
            foreach (DataRow r in dtct.Select("soluong>0"))
                d_tongcong += decimal.Parse(r["soluong"].ToString()) * decimal.Parse(r["giaban"].ToString());
            sotientong.Text = d_tongcong.ToString("###,###,###,##0");
            string s_chu = doiso.Doiso_Unicode(Convert.ToInt64(d_tongcong).ToString());
            chutien.Text = s_chu;
        }
        private void butXoa_Click(object sender, EventArgs e)
        {
            if (kiemtra())
            {
                if (bEdit) m.updrec_toathuocct(dtxoa, int.Parse(stt.Text), l_sttt, i_mabd, mathuoc.Text, tenthuoc.Text, hoatchat.Text, dvt.Text, nguon.Text, nhacc.Text, handung.Text, losx.Text, d_soluongcu,d_giaban, Math.Round(d_soluongcu * d_giaban, 3), int.Parse(makho.Text), int.Parse(manguon.Text), dtton, d_soluongcu, d_sotiencu);
                m.delrec(dtct, "stt=" + int.Parse(stt.Text));
                dtct.AcceptChanges();
                dataGrid1.Refresh();
                if (dtct.Rows.Count == 0) emp_detail();
                else reft_text();
            }
        }
        private void tenthuoc_TextChanged(object sender, EventArgs e)
        {
            if (this.ActiveControl == tenthuoc)
            {
                Filter_dmbd(tenthuoc.Text);
                listthuoc.Tonkhoct_xuatban(tenthuoc, mathuoc, soluong, mathuoc.Location.X, mathuoc.Location.Y - 99, mathuoc.Width + label11.Width + tenthuoc.Width + label12.Width + hoatchat.Width + 22, mathuoc.Height + 5);
            }
        }
        private void Filter_dmbd(string ten)
        {
            try
            {
                CurrencyManager cm = (CurrencyManager)BindingContext[listthuoc.DataSource];
                DataView dv = (DataView)cm.List;
                sql = "(soluong>0) and (ten like '" + ten.Trim() + "%'" + " or tenhc like '" + ten.Trim() + "%')";
                dv.RowFilter = sql;
            }
            catch { }
        }
        private void tenthuoc_Validated(object sender, EventArgs e)
        {
            if (!listthuoc.Focused) listthuoc.Hide();
        }
        private void tenthuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up) listthuoc.Focus();
            else if (e.KeyCode == Keys.Enter)
            {
                if (listthuoc.Visible) listthuoc.Focus();
                else SendKeys.Send("{Tab}");
            }
        }
        private void mathuoc_TextChanged(object sender, EventArgs e)
        {
            if (this.ActiveControl == mathuoc)
            {
                Filter_dmbd(mathuoc.Text);
                listthuoc.Tonkhoct_xuatban(tenthuoc, mathuoc, soluong, mathuoc.Location.X, mathuoc.Location.Y - 99, mathuoc.Width + label11.Width + tenthuoc.Width + label12.Width + hoatchat.Width + 22, mathuoc.Height + 5);
            }	
        }
        private void mathuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up) listthuoc.Focus();
            else if (e.KeyCode == Keys.Enter)
            {
                sql = "ma like '" + mathuoc.Text.Trim() + "%'";
                DataRow[] dr = dtton.Select(sql);
                if (dr.Length == 1)
                {
                    mathuoc.Text = dr[0]["stt"].ToString();
                    get_items(int.Parse(mathuoc.Text));
                    if (!listthuoc.Focused) listthuoc.Hide();
                    soluong.Focus();
                }
                else
                {
                    if (listthuoc.Visible)
                    {
                        listthuoc.Focus();
                        SendKeys.Send("{Up}");
                    }
                    else SendKeys.Send("{Tab}");
                }
            }
        }
        private void get_items(int tt)
        {
            try
            {
                DataRow r = m.getrowbyid(dtton, "stt=" + tt);
                if (r != null)
                {
                    stt.Text = tt.ToString();
                    mathuoc.Text = r["ma"].ToString();
                    tenthuoc.Text = r["ten"].ToString();
                    hoatchat.Text = r["tenhc"].ToString();
                    dvt.Text = r["dang"].ToString();
                    makho.Text = r["makho"].ToString();
                    manguon.Text = r["manguon"].ToString();
                    nguon.Text= r["tennguon"].ToString();
                    d_giaban = decimal.Parse(r["giaban"].ToString());
                    giaban.Text = d_giaban.ToString("###,###,###,##0.00");
                }
            }
            catch { }
        }
        private void listthuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    get_items(int.Parse(mathuoc.Text));
                }
                catch { mathuoc.Focus(); }
            }
        }
        private void butLuu_Click(object sender, EventArgs e)
        {
            if (mathuoc.Text != "" && tenthuoc.Text != "" && stt.Text != "")
            {
                m.updrec_toathuocct(dtct, int.Parse(stt.Text), l_sttt, i_mabd, mathuoc.Text, tenthuoc.Text, hoatchat.Text, dvt.Text, nguon.Text, nhacc.Text, handung.Text, losx.Text, d_soluong, d_giaban, Math.Round(d_soluong * d_giaban, 3), int.Parse(makho.Text), int.Parse(manguon.Text), dtton, d_soluongcu, d_sotiencu);
                dtct.AcceptChanges(); dataGrid1.Refresh();
            }
            l_id = (bNew) ? m.get_capid : l_id;
            int i_sotoa=m.get_sotoa_xuatban(s_mmyy,l_id,s_ngay);
            toaso.Text = i_sotoa.ToString();
            if (!m.upd_toathuocll(s_mmyy, l_id, mabn.Text, l_maql, hoten.Text, namsinh.Text, cboGioitinh.SelectedIndex, s_ngay, mabs.Text, makp.Text, maicd.Text, icd.Text, i_userid, i_sotoa, 0))
            {
                MessageBox.Show("Không cập nhật được thông tin !", DAL.AccessData.Msg); return;
            }
            if (!bNew && bEdit)
            {
                foreach (DataRow r1 in dtxoa.Rows)
                {
                    m.upd_theodoisua(m.get_capid_theodoisua, mabn.Text, l_maql, int.Parse(r1["mabd"].ToString()), r1["ten"].ToString(), decimal.Parse(r1["soluong"].ToString()), i_userid, "NT", "d_toathuocct_" + s_mmyy, 0, 0, 1);
                    m.execute_data("delete from " + user + ".d_toathuocct_"+s_mmyy+" where id=" + l_id + " and stt=" + long.Parse(r1["stt"].ToString()));
                    m.upd_tonkhoct_xuat("delete", s_mmyy, long.Parse(r1["sttt"].ToString()), int.Parse(r1["makho"].ToString()), int.Parse(r1["manguon"].ToString()), int.Parse(r1["mabd"].ToString()), r1["handung"].ToString(), r1["losx"].ToString(),int.Parse(r1["madv"].ToString()), decimal.Parse(r1["soluong"].ToString()), decimal.Parse(r1["sotien"].ToString()), decimal.Parse(r1["giaban"].ToString()), decimal.Parse(r1["giamua"].ToString()));
                }
                foreach (DataRow r in dtthem.Rows)
                    m.upd_theodoisua(m.get_capid_theodoisua, mabn.Text, l_maql, int.Parse(r["id"].ToString()), r["ten"].ToString(), decimal.Parse(r["soluong"].ToString()), i_userid, "NT", "d_toathuocct_" + s_mmyy, 1, 0, 0);
                foreach (DataRow r in dtct.Rows)
                {
                    DataRow nr = m.getrowbyid(dtsave, "mabd=" + int.Parse(r["mabd"].ToString()));
                    if (nr != null)
                    {
                        decimal d_soluong_old = decimal.Parse(nr["soluong"].ToString());
                        if (d_soluong_old != decimal.Parse(r["soluong"].ToString()))
                            m.upd_theodoisua(m.get_capid_theodoisua, mabn.Text, l_maql, int.Parse(r["id"].ToString()), r["ten"].ToString(), d_soluong_old, i_userid, "NT", "d_toathuocct_" + s_mmyy, 0, 1, 0);
                    }
                }
            }
            dtct = m.get_toathuocct(s_mmyy, dtct, l_id);
            m.updrec_toathuocll(dtll, l_id, mabn.Text, hoten.Text, namsinh.Text, s_ngay, mabs.Text, makp.Text, i_userid, i_sotoa, l_maql);
            tongcong_giaban(dtct);
            sotientong.Text = d_tongcong.ToString("###,###,###,##0");
            string s_chu = doiso.Doiso_Unicode(Convert.ToInt64(d_tongcong).ToString());
            chutien.Text = s_chu;
            bNew = false; bEdit = false;
            cboMabn.Visible = true; mabn.Visible = false; cboMabn.BringToFront();
            if (cboMabn.Items.Count > 0) cboMabn.SelectedIndex = dtll.Rows.Count - 1;
            ena_button(false);
            ena_object(false);
            butMoi.Focus();
        }
        private void tongcong_giaban(DataTable dt)
        {
            d_tongcong = 0;
            foreach (DataRow r1 in dt.Select("soluong>0")) d_tongcong += decimal.Parse(r1["sotienban"].ToString());
        }
        private void tongcong(DataTable dt)
        {
            d_tongcong = 0;
            foreach (DataRow r1 in dt.Select("soluong>0")) d_tongcong += decimal.Parse(r1["sotien"].ToString());
        }
        private void butHuy_Click(object sender, EventArgs e)
        {
            try 
            {
                if (m.bKhoaso(s_mmyy))
                {
                    MessageBox.Show("Số liệu tháng" + s_mmyy.Substring(0, 2) + " năm " + s_mmyy.Substring(2, 2) + "đã khóa !\nNếu cần thay đổi thì vào mục khai báo hệ thống!", DAL.AccessData.Msg);
                    return;
                }
                if (l_id == 0) return;
                if (m.get_data("select idduyet from " + m.user + ".d_toathuocll_" + s_mmyy + " where idduyet <>0 and mabn='" + mabn.Text.Trim() + "'").Tables[0].Rows.Count > 0)
                {
                    MessageBox.Show("Toa thuốc này đã được trả, không thể huỷ !");
                    mabn.Focus();
                    return;
                }
                if (MessageBox.Show("Đồng ý hủy số phiếu này ?", DAL.AccessData.Msg, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    l_id = long.Parse(cboMabn.SelectedValue.ToString());
                    foreach (DataRow r1 in dtct.Rows)
                    {
                        m.upd_theodoisua(m.get_capid_theodoisua, mabn.Text, l_maql, int.Parse(r1["mabd"].ToString()), r1["ten"].ToString(), decimal.Parse(r1["soluong"].ToString()), i_userid, "NHATHUOC", "d_toathuocct_" + s_mmyy, 0, 0, 1);
                        m.upd_tonkhoct_xuat("delete", s_mmyy, long.Parse(r1["sttt"].ToString()), int.Parse(r1["makho"].ToString()), int.Parse(r1["manguon"].ToString()), int.Parse(r1["mabd"].ToString()), r1["handung"].ToString(), r1["losx"].ToString(), int.Parse(r1["madv"].ToString()), decimal.Parse(r1["soluong"].ToString()), decimal.Parse(r1["sotienban"].ToString()), decimal.Parse(r1["giaban"].ToString()), decimal.Parse(r1["giamua"].ToString()));
                    }
                    m.execute_data("delete from " + user + ".d_toathuocct_"+s_mmyy+" where id=" + l_id);
                    m.execute_data("delete from " + user + ".d_toathuocll_"+s_mmyy+" where id=" + l_id);
                    m.delrec(dtll, "id=" + l_id);
                    dtll.AcceptChanges();
                    cboMabn.Refresh();
                    try
                    {
                        if (dtll.Rows.Count > 0) cboMabn.SelectedIndex = dtll.Rows.Count - 1;
                    }
                    catch { }
                    if (cboMabn.Items.Count > 0) l_id = long.Parse(cboMabn.SelectedValue.ToString());
                    else l_id = 0;
                    load_head(); load_grid();
                    ena_object(false); cboMabn.BringToFront();
                    butMoi.Focus();
                }
            }
            catch { }
        }
        private void mnuDmkho_Click(object sender, EventArgs e)
        {
            frmDmnhom f = new frmDmnhom(m, "d_dmkho", "id", "ten", "Mã kho", "Tên kho", 16, "Danh mục kho", "makho");
            //f.ShowDialog();
        }
        private void butNhapkho_Click(object sender, EventArgs e)
        {
            //if (this.MdiChildren.Length > 0)
            //{
            //    MessageBox.Show("Bạn đang thao tác trên mục " + get_ten(this.MdiChildren[0].Text.ToString()) + "\nMuốn sử dụng mục khác bạn phải tắt mục đang nhập!", DAL.AccessData.Msg); 
            //    return;
            //}
            if (IsLoaded("frmNhapkho")) return;
            frmNhapkho f = new frmNhapkho(m,s_mmyy,i_userid, s_ngay);
            //f.MdiParent = this;
            f.Show();
            //f.ShowInTaskbar = false;
            f.Dock = DockStyle.Fill;
            f.BringToFront();
            f.Left = pForm.Left;
            f.Top = pForm.Top;
            f.Height = pForm.Height;
            f.Width = pForm.Width;
            pForm.SendToBack();
            pPhieukham.Visible = false;
            lChon.Text = "      " + butNhapkho.Text.ToUpper();
        }
        private void butTrathuoc_Click(object sender, EventArgs e)
        {
            //if (this.MdiChildren.Length > 0)
            //{
            //    MessageBox.Show("Bạn đang thao tác trên mục " + get_ten(this.MdiChildren[0].Text.ToString()) + "\nMuốn sử dụng mục khác bạn phải tắt mục đang nhập!", DAL.AccessData.Msg); 
            //    return;
            //}
            //if (IsLoaded("frmTrathuoc")) return;
            //frmTrathuoc f = new frmTrathuoc(m, "N", s_mmyy, s_ngay, i_userid, "");
            //f.MdiParent = this;
            //f.Show();
            //f.ShowInTaskbar = false;
            //f.Dock = DockStyle.Fill;
            //f.BringToFront();
            //f.Left = pForm.Left;
            //f.Top = pForm.Top;
            //f.Height = pForm.Height;
            //f.Width = pForm.Width;
            pForm.SendToBack();
            pPhieukham.Visible = false;
            lChon.Text = "      " + butTrathuoc.Text.ToUpper();
        }
        private void mnuPhanquyen_Click(object sender, EventArgs e)
        {

        }
        private void danhMụcNguồnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmDmnhom f = new frmDmnhom(m, "d_dmnguon", "id", "ten", "Mã nguồn", "Tên nguồn", 17, "Danh mục nguồn", "manguon");
            //f.ShowDialog();
        }
        private void soluong_Validated(object sender, EventArgs e)
        {
            try
            {
                d_soluong = (soluong.Text != "") ? decimal.Parse(soluong.Text) : 0;
                soluong.Text = d_soluong.ToString("###,###,##0.0");
                if (mathuoc.Text != "" && tenthuoc.Text != "")
                {
                    DataRow r = m.getrowbyid(dtton, "ma='" + mathuoc.Text + "'");
                    if (r != null)
                    {
                        i_mabd = int.Parse(r["id"].ToString());
                        d_soluongton = m.get_slton_nguon(dtton, int.Parse(makho.Text), i_mabd, int.Parse(manguon.Text), d_soluongcu);
                        if (d_soluong > d_soluongton)
                        {
                            MessageBox.Show("Số lượng xuất lớn hơn số lượng tồn !(" + d_soluongton.ToString() + ")", DAL.AccessData.Msg);
                            soluong.Focus();
                            return;
                        }
                    }
                }
            }
            catch { }
            tinh_giatri();
            if (soluong.Text == "" || soluong.Text == "0.00" || soluong.Text == "0") return;
            if (bEdit) butThem_Click(null, null);
        }
        private void tinh_giatri()
        {
            try
            {
                d_soluong = (soluong.Text != "") ? decimal.Parse(soluong.Text) : 0;
                d_dongia = (giamua.Text != "") ? decimal.Parse(giamua.Text) : 0;
                d_giaban = (giaban.Text != "") ? decimal.Parse(giaban.Text) : 0;
                d_sotienban = Math.Round(d_soluong * d_giaban, 3);
                d_sotien = Math.Round(d_soluong * d_dongia, 3);
                sotienban.Text = d_sotienban.ToString("###,###,##0.00");
                sotien.Text = d_sotien.ToString("###,###,##0.00");
            }
            catch { }
        }
        private void soluong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                butThem.Focus();
            }
        }
        private void cboMabn_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                butMoi.Focus();
            }
        }
        private void sotientong_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
        }
        private void mnuTondau_Click(object sender, EventArgs e)
        {
            //if (this.MdiChildren.Length > 0)
            //{
            //    MessageBox.Show("Bạn đang thao tác trên mục " + get_ten(this.MdiChildren[0].Text.ToString()) + "\nMuốn sử dụng mục khác bạn phải tắt mục đang nhập!", DAL.AccessData.Msg); 
            //    return;
            //}
            frmChonkho fi = new frmChonkho(m);
            //fi.ShowDialog();
            if (fi.i_makho != 0)
            {
                if (IsLoaded("frmNhapkho")) return;
                frmKhaitondau f = new frmKhaitondau(m, fi.s_mmyy, fi.i_makho, i_userid);
                //f.MdiParent = this;
                f.Show();
                //f.ShowInTaskbar = false;
                f.Dock = DockStyle.Fill;
                f.BringToFront();
                f.Left = pForm.Left;
                f.Top = pForm.Top;
                f.Height = pForm.Height;
                f.Width = pForm.Width;
                pForm.SendToBack();
                pPhieukham.Visible = false;
                lChon.Text = "      " + mnuTondau.Text.ToUpper() + " - " + fi.s_tenkho.ToUpper();
            }
        }
        private void mnuThekho_Click(object sender, EventArgs e)
        {
            //frmThekho f = new frmThekho(m, s_makho, s_mmyy, "d_thekho.rpt", "Thẻ kho");
            //f.ShowDialog();
        }
        private void mnuDoingay_Click(object sender, EventArgs e)
        {
            frmDoingay f = new frmDoingay();
            //f.ShowDialog(this);
            if (f.s_mmyy != "")
            {
                s_mmyy = f.s_mmyy;
                s_ngay = f.s_ngay.Substring(0, 10);
                ngaylamviec.Value = DateTime.Parse(f.s_ngay).Date;
                load_sophieu();
            }
        }
        private void toaso_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                mathuoc.Focus();
            }
        }
        private void butIn_Click(object sender, EventArgs e)
        {
            if (dtct.Rows.Count == 0) return;
            string s_tenkho = makho.Text;
            frmReport f = new frmReport(m, dtct, "", "d_toathuoc.rpt", cboMabn.Text, hoten.Text, "", "", s_ngay, "" , "", "", "", "", "", "");
            f.Title = "Toa thuốc";
            this.FormMain.OpenTab( f);
        }
        private void toaso_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
        }
        private void timkiem_TextChanged(object sender, EventArgs e)
        {
            if (this.ActiveControl == timkiem && timkiem.Text.Trim() != "Tìm kiếm")
            {
                try
                {
                    CurrencyManager cm = (CurrencyManager)BindingContext[cboMabn.DataSource];
                    DataView dv = (DataView)cm.List;
                    dv.RowFilter = "mabn like '%" + timkiem.Text.Trim() + "%'";
                    if (cboMabn.Items.Count > 0) l_id = long.Parse(cboMabn.SelectedValue.ToString());
                    load_head(); load_grid();
                    reft_text(); sum_sotienban();
                }
                catch { }
            }
        }

        private void mnuTraNCC_Click(object sender, EventArgs e)
        {
            //if (this.MdiChildren.Length > 0)
            //{
            //    MessageBox.Show("Bạn đang thao tác trên mục " + get_ten(this.MdiChildren[0].Text.ToString()) + "\nMuốn sử dụng mục khác bạn phải tắt mục đang nhập!", DAL.AccessData.Msg); 
            //    return;
            //}
            //if (IsLoaded("frmNhapkho")) return;
            frmHoantrancc f = new frmHoantrancc(m, "HT", s_mmyy, s_ngay, i_userid);
            //f.MdiParent = this;
            f.Show();
            //f.ShowInTaskbar = false;
            f.Dock = DockStyle.Fill;
            f.BringToFront();
            f.Left = pForm.Left;
            f.Top = pForm.Top;
            f.Height = pForm.Height;
            f.Width = pForm.Width;
            pForm.SendToBack();
            pPhieukham.Visible = false;
            lChon.Text = "      " + mnuTraNCC.Text.ToUpper();
        }
        private string get_ten(string form)
        {
            string s = "";
            switch (form.ToLower())
            {
                case "frmnhapkho": s = "Phiếu nhập kho"; break;
                case "frmhoantrancc": s = "Hoàn trả nhà cung cấp"; break;
                case "frmtrathuoc": s = "Phiếu trả thuốc"; break;
                case "frmkhaitondau": s = "Khai báo tồn đầu kho"; break;
                case "frmdmthuoc": s = "Khai báo danh mục thuốc"; break;
            }
            return s;
        }
    }
}